package com.share.PACManager.task;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.share.PACManager.model.NoticeModel;
import com.share.PACManager.model.TerminalModel;
import com.share.PACManager.net.HTTPResponse;
import com.share.PACManager.net.HttpUtility;
import com.share.PACManager.utils.Cryptography;
import com.share.PACManager.utils.Utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;


public class GetNoticesTask extends Thread{

	private GetNoticesListener mListener;
	private Context mContext;	
	private TerminalModel mTerminal;
	private String mLastTime;
	private List<NoticeModel> mNotices;
	private boolean bLoop;
	
	public interface GetNoticesListener {
		public TerminalModel requestTerminal();
		public String requestLastTime();		
		public void onCheckResult(boolean result, List<NoticeModel> list);
	}

	public GetNoticesTask(Context context) {
		mContext = context;
	}
	
	public void start(GetNoticesListener listener) {
		mListener = listener;
		if(mListener != null)
		{
			mTerminal = mListener.requestTerminal();
			
			start();
		}
	}

	public void startLoop(GetNoticesListener listener) {
		bLoop = true;
		start(listener);
	}
	
	private boolean bPause;
	public void pauseThread()
	{
		bPause = true;
	}
	public void resumeThread()
	{
		bPause = false;
	}
	
	private Handler handler = new Handler(){		
		@Override
		public void handleMessage(Message msg)
		{
			if(mListener != null)
			{
				if(msg.what != 0)
					mListener.onCheckResult(false, mNotices);
				else
				{
					HTTPResponse resp = (HTTPResponse) msg.obj;
					mListener.onCheckResult(parse(resp.content), mNotices);								
				}
			}
		}
	};
	
    public boolean parse(String json)
    {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if(!jsonObject.getBoolean("Success"))
				return false;
			
			JSONArray state = jsonObject.getJSONArray("State"); 
			if(state != null)
			{
				mNotices = new ArrayList<NoticeModel>();
				for(int i = 0 ; i < state.length(); i++)
				{
					JSONObject object = state.getJSONObject(i);		
					NoticeModel notice = new NoticeModel();		
					
					notice.NoticeId = Utils.getJsonString(object, "NoticeId");
					notice.NoticeType = Utils.getJsonString(object, "NoticeType");
					notice.NoticeArea = Utils.getJsonString(object, "NoticeArea");
					notice.NoticeTitle = Utils.getJsonString(object, "NoticeTitle");
					notice.NoticeContent = Utils.getJsonString(object, "NoticeContent");
					notice.NoticeAuthor = Utils.getJsonString(object, "NoticeAuthor");
					notice.NoticeCreateTime = Utils.getJsonDate(object,"NoticeCreateTime");
					notice.NoticeEffectiveTime = Utils.getJsonDate(object,"NoticeEffectiveTime");
					notice.NoticeComment = Utils.getJsonString(object, "NoticeComment");
					
					mNotices.add(notice);
				}				
			}
			return true;			
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return false;
    }
    
    public void stopRun()
    {
    	bLoop = false;
    }
    
	@Override
	public void run() {

		while(true)
		{
			try {	
				if(!bPause)
				{
					mLastTime = mListener.requestLastTime();
					String terminalId = mTerminal.TerminalId;
					String imei = mTerminal.TerminalCode;
					String password = mTerminal.TerminalPassword;
					String ticket = Cryptography.AES_Encode(imei, terminalId, password);
					String info = Cryptography.AES_Encode("LastModified="+mLastTime, terminalId, password);
					String entity = "Information=" + URLEncoder.encode(info);
					
					Map<String, String> params = new TreeMap<String, String>();
					params.put("Id", terminalId);
					params.put("TerminalId", terminalId);
					params.put("DataType", "Data");	
					params.put("Password", password);
					params.put("TerminalCode", imei);
					params.put("Version", "1.0");
					params.put("Ticket", ticket);
					params.put("Objective", "GetNotices");
							
					handler.obtainMessage(0, HttpUtility.httpPost(params, entity)).sendToTarget();
					if(!bLoop)
						break;				
					Thread.sleep(5*1000);
				}
				else
				{
					Thread.sleep(1000);
				}	
			} catch (Exception e) {
				handler.obtainMessage(1).sendToTarget();
			}
		}		
		super.run();
	}
}
